package xdu.lz.stage5_jucUtils.chapter3_exchanger;

import java.util.concurrent.Exchanger;

/**
 * Created at 2019/10/19 0019 上午 11:03
 */
public class Exchanger3 {
    public static void main(String[] args) {

        Exchanger<Object> exchanger = new Exchanger<>();
        /**
         * 注意：两者交换的是同一个对象，要考虑线程安全问题，如果是集合，那么可能会双方进行CRUD出现thread-safe
         */
        new Thread(()->{
            try {
                Object aobj = new Object();
                System.out.println("T1 send:"+aobj);
                //调用该API后阻塞住，直到检测到其他线程达到exchange point
                Object res = exchanger.exchange(aobj);
                System.out.println(Thread.currentThread().getName()+" receive:"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();

        new Thread(()->{
            try {
                Object bobj = new Object();
                System.out.println("T2 send:"+bobj);
                //调用该API后阻塞住，直到检测到其他线程达到exchange point
                Object res = exchanger.exchange(bobj);
                System.out.println(Thread.currentThread().getName()+" receive:"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}
